package guanli;

import until.DBUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;

public class ParcelManagePanel extends JPanel {
    private JTable table;
    private DefaultTableModel model;
    // 与表结构一致的状态枚举值
    private final String[] STATUS_OPTIONS = {"未取", "已取", "未寄出", "已寄出"};

    public ParcelManagePanel() {
        setLayout(new BorderLayout());

        JLabel title = new JLabel("快递柜包裹管理", SwingConstants.CENTER);
        title.setFont(new Font("微软雅黑", Font.BOLD, 22));
        add(title, BorderLayout.NORTH);

        model = new DefaultTableModel(new String[]{
                "ID", "手机号", "尺寸", "取件码", "柜子ID", "状态", "创建时间", "取件时间"
        }, 0);
        table = new JTable(model);
        loadData();

        add(new JScrollPane(table), BorderLayout.CENTER);

        JPanel btnPanel = new JPanel();
        JButton btnAdd = new JButton("添加包裹");
        JButton btnDelete = new JButton("删除包裹");
        JButton btnRefresh = new JButton("刷新");

        btnAdd.addActionListener(e -> addParcel());
        btnDelete.addActionListener(e -> deleteParcel());
        btnRefresh.addActionListener(e -> loadData());

        btnPanel.add(btnAdd);
        btnPanel.add(btnDelete);
        btnPanel.add(btnRefresh);

        add(btnPanel, BorderLayout.SOUTH);
    }

    private void loadData() {
        model.setRowCount(0);
        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             // 显式指定字段，处理pickup_time为NULL的情况
             ResultSet rs = stmt.executeQuery(
                     "SELECT id, phone, size, code, locker_id, status, " +
                             "DATE_FORMAT(create_time, '%Y-%m-%d %H:%i:%s') AS create_time, " +
                             "IFNULL(DATE_FORMAT(pickup_time, '%Y-%m-%d %H:%i:%s'), '无') AS pickup_time " +
                             "FROM parcels")) {

            while (rs.next()) {
                model.addRow(new Object[]{
                        rs.getInt("id"),
                        rs.getString("phone"),
                        rs.getString("size"),
                        rs.getString("code"),
                        rs.getInt("locker_id"),
                        rs.getString("status"),
                        rs.getString("create_time"),
                        rs.getString("pickup_time")
                });
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this,
                    "加载包裹数据失败: " + e.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    private void addParcel() {
        JTextField phoneField = new JTextField();
        JTextField sizeField = new JTextField();
        JTextField codeField = new JTextField();
        JTextField lockerField = new JTextField();
        JComboBox<String> statusBox = new JComboBox<>(STATUS_OPTIONS); // 使用与表一致的状态

        JPanel panel = new JPanel(new GridLayout(0, 2));
        panel.add(new JLabel("手机号:"));
        panel.add(phoneField);
        panel.add(new JLabel("尺寸:"));
        panel.add(sizeField);
        panel.add(new JLabel("取件码:"));
        panel.add(codeField);
        panel.add(new JLabel("柜子ID:"));
        panel.add(lockerField);
        panel.add(new JLabel("状态:"));
        panel.add(statusBox);

        int result = JOptionPane.showConfirmDialog(this, panel, "添加包裹", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            String phone = phoneField.getText().trim();
            String size = sizeField.getText().trim();
            String code = codeField.getText().trim();
            String lockerIdStr = lockerField.getText().trim();
            String status = (String) statusBox.getSelectedItem();

            // 输入验证
            if (phone.isEmpty() || size.isEmpty() || code.isEmpty() || lockerIdStr.isEmpty()) {
                JOptionPane.showMessageDialog(this, "请填写所有字段", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            if (!lockerIdStr.matches("\\d+")) {
                JOptionPane.showMessageDialog(this, "柜子ID必须是数字", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            int lockerId = Integer.parseInt(lockerIdStr);

            // 验证柜子ID是否存在（外键约束预处理）
            if (!validateLockerExists(lockerId)) {
                return;
            }

            try (Connection conn = DBUtil.getConnection();
                 PreparedStatement ps = conn.prepareStatement(
                         "INSERT INTO parcels (phone, size, code, locker_id, status) " +
                                 "VALUES (?, ?, ?, ?, ?)",
                         Statement.RETURN_GENERATED_KEYS)) { // 预留获取自增ID

                ps.setString(1, phone);
                ps.setString(2, size);
                ps.setString(3, code);
                ps.setInt(4, lockerId);
                ps.setString(5, status);

                int rowsAffected = ps.executeUpdate();
                if (rowsAffected > 0) {
                    JOptionPane.showMessageDialog(this, "包裹添加成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                    loadData();
                }
            } catch (SQLException e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this,
                        "添加失败: " + e.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private boolean validateLockerExists(int lockerId) {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(
                     "SELECT COUNT(*) FROM lockers WHERE id = ?")) {

            ps.setInt(1, lockerId);
            ResultSet rs = ps.executeQuery();
            rs.next();
            if (rs.getInt(1) == 0) {
                JOptionPane.showMessageDialog(this, "柜子ID不存在，请检查输入！", "错误", JOptionPane.ERROR_MESSAGE);
                return false;
            }
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this,
                    "验证柜子ID失败: " + e.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
            return false;
        }
    }

    private void deleteParcel() {
        int row = table.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要删除的包裹", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int id = (int) model.getValueAt(row, 0);
        int confirm = JOptionPane.showConfirmDialog(this, "确认删除包裹记录？", "确认", JOptionPane.YES_NO_OPTION);

        if (confirm == JOptionPane.YES_OPTION) {
            try (Connection conn = DBUtil.getConnection();
                 PreparedStatement ps = conn.prepareStatement("DELETE FROM parcels WHERE id = ?")) {

                ps.setInt(1, id);
                int rowsAffected = ps.executeUpdate();
                if (rowsAffected > 0) {
                    JOptionPane.showMessageDialog(this, "包裹删除成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                    loadData();
                }
            } catch (SQLException e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this,
                        "删除失败: " + e.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}